using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Decav.Gatsb.Application;
using Decav.Gatsb;

public partial class SetLocationWidget : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        setLocationErrorRibbon.Visible = false;
        if (!IsPostBack)
            UpdateLocationText();
    }

    protected void SaveLocationButton_Click(object sender, EventArgs e)
    {
        // Take this as clearing the location.
        if (changeLocationTextBox.Text.Trim() == string.Empty)
        {
            ClearLocationButton_Click(sender, e);
            return;
        }

        // Conduct a search for the location.
        Location[] results = GatsbApplication.Current.FindLocation(
            LocationSearchCriteria.Parse(changeLocationTextBox.Text));

        if (results.Length == 0)
        {
            ClearLocationButton_Click(sender, e);
            setLocationErrorRibbon.Visible = true;

            createLocationHref.HRef = string.Format("~/CreateLocation.aspx?name={0}", Server.UrlEncode(changeLocationTextBox.Text));
            createLocationHref.InnerText = string.Format("create \"{0}\"", changeLocationTextBox.Text);
        }
        else if (results.Length == 1)
        {
            GatsbApplication.Current.SetUserLocation(results[0].Id);
        }
        else
        {
            Response.Redirect(
                string.Format("~/Search.aspx?q={0}&postalCode={1}",
                Server.UrlEncode(changeLocationTextBox.Text),
                GatsbApplication.Current.CurrentUser.PostalCode),
                true);
        }

        UpdateLocationText();
        changeLocationTextBox.Text = string.Empty;
    }

    protected void ClearLocationButton_Click(object sender, EventArgs e)
    {
        GatsbApplication.Current.ClearUserLocation();
        UpdateLocationText();
    }

    private void UpdateLocationText()
    {
        if (!GatsbApplication.Current.UserPresent)
        {
            Visible = false;
            return;
        }

        LocationCheckin location = GatsbApplication.Current.GetUserLocation(GatsbApplication.Current.CurrentUser);
        if (!location.LocationSpecified)
        {
            noLocationDiv.Visible = true;
            locationTextDiv.Visible = false;
        }
        else
        {
            noLocationDiv.Visible = false;
            locationTextDiv.Visible = true;
            currentLocationHref.HRef = string.Format("Place.aspx?id={0}", location.Location.Id);
            currentLocationHref.InnerText = location.Location.ToString();
        }
    }
}
